@using Blog;
@{
    // Require authentication
    WebSecurity.RequireAuthenticatedUser();
    //Edit user basic user settings
    // SET THE VIEW
    var View ="~/Views/Admin/Account/_EditUserSettingsView.cshtml";
    // GET CURRENT USER ID
    var UserId = WebSecurity.CurrentUserId;

    // SET VARS
    string DisplayName,Email,Bio,OldPassword,NewPassword,NewPasswordConfirm;
    string SuccessMessage="";
    // MANAGE POST
    if(IsPost){
        DisplayName = Request.Form["DisplayName"];
        Email = Request.Form["Email"];
        Bio = Request.Form["Bio"];
        OldPassword = Request.Form["OldPassword"];
        NewPassword = Request.Form["NewPassword"];
        NewPasswordConfirm = Request.Form["NewPasswordConfirm"];
        if(DisplayName.IsEmpty()){ModelState.AddFormError("Display name cannot be empty");}
        if(Email.IsEmpty()&& !Utils.IsEmailAdress(Email)){ModelState.AddFormError("Email is not valid");}
        if(Bio.IsEmpty()){ModelState.AddFormError("Bio name cannot be empty");}
        
        
        // if NewPassword is not empty , it means that the user wants to change his password
        if(!(NewPassword.IsEmpty()&&OldPassword.IsEmpty())){
            // validate passwords
            if(OldPassword.IsEmpty()){ModelState.AddFormError("Enter you old password");}
            if(NewPassword!=NewPasswordConfirm){ModelState.AddFormError("New Password and New Password confirmation do not match");}
                // if valid send the changes        
                if(ModelState.IsValid){
                    // try to update password , if failed add form error
                    if(!WebSecurity.ChangePassword(WebSecurity.CurrentUserName, OldPassword, NewPassword)) {
                        ModelState.AddFormError("Password not changed");
                    }else{
                        SuccessMessage +="Password successfully updated</br>";
                    }
            
            }
        }
        // everythings right, update user's profile
        if(ModelState.IsValid){
            var UpdateUserProfile = DataObject.UpdateUserProfileByUserId(UserId.ToString(),DisplayName,Email,Bio); 
            if (UpdateUserProfile>0){
                // success
                SuccessMessage +="Profile successfully updated</br>";
            }else{
                // failure
                ModelState.AddFormError("Query Failed , profile was not updated");
            }
        }
        

            
    }
    // GET USER DETAILS at the end so the view reflects the changes
    var User = DataObject.GetCurrentUserProfile(UserId.ToString());
@RenderPage(View,new{User = User,ModelState=ModelState,SuccessMessage=SuccessMessage});
}
